package jwt

import (
	"blog/util"
	"blog/util/e"
	"net/http"

	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
)

//返回值处理中间件的函数
func JWT() gin.HandlerFunc{
	//gin.Context是gin 中最重要的部分, 用于传递变量, 管理流程, 验证json
	return func(c *gin.Context){
		var code int
		var data interface{}

		code = e.SUCCESS
		//获取请求的token
		token:=c.Query("token")
		if token == ""{
			code=e.INVALID_PARAMS
		}else{
			_,err:=util.ParseToken(token)
			if err != nil{
				switch err.(*jwt.ValidationError).Errors{
				case jwt.ValidationErrorExpired:
					code = e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT
				default:
					code = e.ERROR_AUTH_CHECK_TOKEN_FAIL
				}
			}
		}

		if code!=e.SUCCESS{
			c.JSON(http.StatusUnauthorized,gin.H{
				"code": code,
				"msg":  e.GetMsg(code),
				"data": data,
			})

			c.Abort()
			return
		}

		c.Next()
	}
}